/**
 * 
 */
package com.zhiteng.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhiteng.entity.Item;
import com.zhiteng.entity.Order;
import com.zhiteng.entity.Teacher;
import com.zhiteng.mapper.OrderMapper;
import com.zhiteng.service.ItemService;
import com.zhiteng.service.OrderService;
import com.zhiteng.service.TeacherService;
import com.zhiteng.utils.common.IDUtils;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**  
* <p>Title: OrderServiceImpl.java</p>  
* <p>Description: 订单Service</p>  
* @author dragon  
* @date 2018年12月27日  
* @version 1.0  
*/
@Service
public class OrderServiceImpl implements OrderService {
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private ItemService itemService;
	@Autowired
	private TeacherService teacherService;

	@Override
	public int saveOrder(Order order) {
		Teacher teacher = teacherService.queryTeacherById(order.getTeacherId());
		Item item = itemService.queryItemById(order.getItemId());
		
		if(item==null) return -1;
		if(item.getNum()<=0) return -2;
		if(teacher==null) return -3;
		if(teacher.getBonusPoint()<item.getPrice()) return -4;
		
		order.setId(IDUtils.genItemId());
		order.setCreated(new Date());
		order.setItemTitle(item.getTitle());
		order.setImage(item.getImage());
		order.setPrice(item.getPrice());
		order.setRule(item.getRule());
		order.setStatus(0); //	未领取
		
		//	1、保存订单信息
		int result = orderMapper.insert(order);
		
		//	2、积分礼品数量减一
		item.setNum(item.getNum()-1);
		itemService.updateItem(item);
		
		//	3、老师的积分扣除
		teacher.setBonusPoint(teacher.getBonusPoint()-item.getPrice());
		teacherService.updateTeacher(teacher);
		
		
		if(item.getFlag()==0 && item.getNum()==0) {	//	积分礼品数为0时是否删除：0-删除  1-不删除
			itemService.deleteItemById(item.getId());
		}
		return result;
	}

	@Override
	public List<Order> queryOrdersByTeacherId(String teacherId) {
		Example example = new Example(Order.class);
		example.orderBy("created").desc();	//	按订单创建时间降序排列
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("teacherId", teacherId);
		return orderMapper.selectByExample(example);
	}

	@Override
	public int changeOrderStauts(Long orderId, Integer status) {
		Order order = new Order();
		order.setId(orderId);
		order.setStatus(status);
		return orderMapper.updateByPrimaryKeySelective(order);
	}
	
}
